# 战斗管理器 - 控制整个战斗流程
class_name BattleManager

# 移除对BattleUI的预加载，避免在脚本加载阶段遇到问题

# 模式枚举
enum BattleMode { COMMAND_PHASE, ACTION_PHASE }  # 指令安排阶段  # 行动执行阶段

# 战斗状态枚举
enum BattleState { PREPARING, TURN_ORDER, PLAYER_TURN, ENEMY_TURN, RESOLVING, VICTORY, DEFEAT }

# 当前战斗模式
var current_mode: BattleMode = BattleMode.COMMAND_PHASE

# 存储玩家角色的指令
var player_commands: Dictionary = {}

# 战斗相关节点引用
var battle_scene: Node
var player_team_container: HBoxContainer
var enemy_team_container: HBoxContainer

# 战斗数据
var player_characters: Array = []  # 玩家角色数组
var enemy_characters: Array = []  # 敌人角色数组
var turn_order: Array = []  # 回合顺序队列
var current_turn_index: int = 0
var current_state: BattleState = BattleState.PREPARING
var battle_ui: Control = null  # 战斗UI组件
var battle_log: Array = []  # 战斗日志数据


# 初始化战斗管理器
func _init(scene_ref: Node):
	battle_scene = scene_ref
	battle_ui = null
	_setup_scene_references()


# 设置场景引用
func _setup_scene_references():
	player_team_container = battle_scene.get_node("PlayerTeamContainer")
	enemy_team_container = battle_scene.get_node("EnemyTeamContainer")


# 设置战斗UI引用（初始化后使用）
func set_battle_ui(ui_node: Control) -> void:
	# 断开之前的信号连接
	if battle_ui:
		if battle_ui.has_signal("attack_pressed"):
			battle_ui.attack_pressed.disconnect(handle_attack_command)
		if battle_ui.has_signal("skill_pressed"):
			battle_ui.skill_pressed.disconnect(handle_skill_command)
		if battle_ui.has_signal("defend_pressed"):
			battle_ui.defend_pressed.disconnect(handle_defend_command)
		if battle_ui.has_signal("item_pressed"):
			battle_ui.item_pressed.disconnect(handle_item_command)
		if battle_ui.has_signal("target_selected"):
			battle_ui.target_selected.disconnect(handle_target_selected)
		if battle_ui.has_signal("cancel_target_selection"):
			battle_ui.cancel_target_selection.disconnect(handle_cancel_target_selection)

	# 设置新的UI引用
	battle_ui = ui_node

	# 连接信号
	if battle_ui:
		if battle_ui.has_signal("attack_pressed"):
			battle_ui.attack_pressed.connect(handle_attack_command)
		if battle_ui.has_signal("skill_pressed"):
			battle_ui.skill_pressed.connect(handle_skill_command)
		if battle_ui.has_signal("defend_pressed"):
			battle_ui.defend_pressed.connect(handle_defend_command)
		if battle_ui.has_signal("item_pressed"):
			battle_ui.item_pressed.connect(handle_item_command)
		if battle_ui.has_signal("target_selected"):
			battle_ui.target_selected.connect(handle_target_selected)
		if battle_ui.has_signal("cancel_target_selection"):
			battle_ui.cancel_target_selection.connect(handle_cancel_target_selection)


# 初始化战斗
func start_battle(players: Array, enemies: Array):
	player_characters = players
	enemy_characters = enemies
	current_state = BattleState.PREPARING
	battle_log.clear()
	current_mode = BattleMode.COMMAND_PHASE
	player_commands.clear()

	# 初始化UI状态：显示命令面板，隐藏战斗日志
	if battle_ui and battle_ui.has_method("switch_to_command_mode"):
		battle_ui.switch_to_command_mode()

	# 添加战斗开始日志
	add_battle_log("战斗开始！", Color(0.5, 0.8, 1, 1))

	# 确定回合顺序但不开始战斗
	determine_turn_order_without_start()

	# 禁用指令UI，直到战斗场景初始化完成指令跟踪
	if battle_ui:
		disable_command_ui()


# 确定回合顺序但不开始战斗
func determine_turn_order_without_start():
	current_state = BattleState.TURN_ORDER
	turn_order.clear()

	# 收集所有角色并计算 Initiative
	var all_characters = []

	for player in player_characters:
		if player.is_alive:
			all_characters.append({"character": player, "initiative": player.get_initiative()})

	for enemy in enemy_characters:
		if enemy.is_alive:
			all_characters.append({"character": enemy, "initiative": enemy.get_initiative()})

	# 按 Initiative 排序（降序）
	all_characters.sort_custom(_sort_by_initiative)

	# 提取排序后的角色
	for entry in all_characters:
		turn_order.append(entry["character"])

	current_turn_index = 0

	# 显示回合顺序日志
	var order_text = "回合顺序："
	for combatant in turn_order:
		order_text += combatant.name + " > "
	add_battle_log(order_text.substr(0, order_text.length() - 3), Color(0.8, 0.5, 1, 1))

	# 通知用户可以开始安排指令
	add_battle_log("请为所有角色安排指令！", Color(0.8, 0.8, 0.2, 1))


# 确定回合顺序
func determine_turn_order():
	determine_turn_order_without_start()
	print("确定回合顺序")
	# 切换到行动执行阶段
	current_mode = BattleMode.ACTION_PHASE
	if battle_ui and battle_ui.has_method("switch_to_log_mode"):
		battle_ui.switch_to_log_mode()
	print("开始第一个回合")
	# 开始第一个回合
	proceed_to_next_turn()


# Initiative排序函数
static func _sort_by_initiative(a, b):
	if a["initiative"] > b["initiative"]:
		return -1
	if a["initiative"] < b["initiative"]:
		return 1
	return 0


# 进行到下一回合
func proceed_to_next_turn():
	# 检查战斗是否结束
	if _check_battle_end():
		return
	print("找到下一个存活的角色")
	# 找到下一个存活的角色
	while true:
		if current_turn_index >= turn_order.size():
			current_turn_index = 0
			print("回合结束，重新进入指令安排阶段")
			# 回合结束，重新进入指令安排阶段
			current_mode = BattleMode.COMMAND_PHASE
			if battle_ui and battle_ui.has_method("switch_to_command_mode"):
				battle_ui.switch_to_command_mode()

			# 通知用户可以开始安排下一回合的指令
			add_battle_log("回合结束！请为所有角色安排新的指令！", Color(0.2, 0.8, 0.2, 1))

			# 清空之前的指令
			player_commands.clear()

			# 调用战斗场景的回合结束方法，重新初始化指令跟踪
			if battle_scene and battle_scene.has_method("on_turn_end"):
				battle_scene.on_turn_end()
			return

		var current_character = turn_order[current_turn_index]
		current_turn_index += 1
		print("current_character", current_character.is_player, current_character.is_alive)
		if current_character.is_alive:
			# 根据角色类型设置战斗状态
			print("根据角色类型设置战斗状态")
			if current_character.is_player:
				current_state = BattleState.PLAYER_TURN
				print("玩家行动")
				add_battle_log("%s的回合！" % current_character.name, Color(0.8, 0.5, 1, 1))
				# 启用命令UI前添加延时，展示战斗动画
				print("再次启用命令UI")
				_enable_command_ui(true)
				await battle_scene.get_tree().create_timer(1.5).timeout  # 调整延时为1.5秒
				print("命令UI已启用，等待玩家输入")
			else:
				current_state = BattleState.ENEMY_TURN
				print("敌人行动")
				add_battle_log("%s的回合！" % current_character.name, Color(1, 0.5, 0.5, 1))
				# 禁用命令UI
				_enable_command_ui(false)
				# 敌人AI行动
				print("执行敌人AI行动")
				_process_enemy_turn(current_character)
				print("敌人AI行动执行完毕")
				# 敌人行动前添加延时，展示战斗动画
				print("开始敌人行动前延时")
				await battle_scene.get_tree().create_timer(1.5).timeout  # 调整延时为1.5秒
				print("敌人行动前延时结束")
			# break


# 处理玩家行动
func process_player_action(action_type: String, target: Character = null):
	if current_state != BattleState.PLAYER_TURN:
		return false

	var current_character = turn_order[current_turn_index]
	current_state = BattleState.RESOLVING

	# 执行玩家行动
	match action_type:
		"attack":
			if target and target.is_alive:
				var damage = current_character.attack
				var actual_damage = target.take_damage(damage)
				add_battle_log(
					"%s对%s造成了%d点伤害！" % [current_character.name, target.name, actual_damage],
					Color(1, 0.5, 0.5, 1)
				)
		"skill":
			# 这里简化处理，实际应该有选择技能的界面
			pass
		"defend":
			add_battle_log("%s进入了防御状态！" % current_character.name, Color(0.8, 0.8, 0.8, 1))
		"item":
			# 这里简化处理，实际应该有选择物品的界面
			pass

	# 行动完成，进入下一回合
	await battle_scene.get_tree().create_timer(1.0).timeout  # 等待1秒显示结果
	proceed_to_next_turn()
	return true


# UI命令处理函数
var pending_command_type: String = ""
var pending_command_player: Character = null


func handle_attack_command():
	print("攻击按钮被点击")
	# 在指令安排阶段，显示目标选择UI
	if current_mode == BattleMode.COMMAND_PHASE:
		# 找到当前未分配指令的玩家角色
		pending_command_player = null
		for player in player_characters:
			if player.is_alive and player.name not in player_commands:
				pending_command_player = player
				break

		if pending_command_player:
			pending_command_type = "attack"
			# 收集所有存活敌人的节点
			var alive_enemy_nodes = []
			for enemy in enemy_characters:
				if enemy.is_alive and enemy.node:
					alive_enemy_nodes.append(enemy.node)

			if alive_enemy_nodes.size() > 0:
				# 显示目标选择UI
				if battle_ui and battle_ui.has_method("show_target_selection"):
					battle_ui.show_target_selection(alive_enemy_nodes)
			else:
				# 如果没有目标选择UI，默认选择第一个敌人
				var target = null
				for enemy in enemy_characters:
					if enemy.is_alive:
						target = enemy
						break
				if target != null:
					store_player_command(pending_command_player, "attack", target)

	else:
		# 在行动执行阶段，直接处理
		var target = null
		for enemy in enemy_characters:
			if enemy.is_alive:
				target = enemy
				break

		if target != null:
			process_player_action("attack", target)


func handle_target_selected(character_node: Node) -> void:
	"""处理目标选择"""
	if pending_command_type and pending_command_player:
		# 根据节点找到对应的角色对象
		var target_character = null
		for enemy in enemy_characters:
			if enemy.node == character_node:
				target_character = enemy
				break

		if target_character:
			# 使用更新后的函数存储玩家命令
			store_player_command(pending_command_player, pending_command_type, target_character)

			# 重置pending状态
			pending_command_type = ""
			pending_command_player = null

			# 隐藏目标选择UI
			if battle_ui and battle_ui.has_method("hide_target_selection"):
				battle_ui.hide_target_selection()


func handle_cancel_target_selection() -> void:
	"""处理取消目标选择"""
	# 重置pending状态
	pending_command_type = ""
	pending_command_player = null

	# 隐藏目标选择UI
	if battle_ui and battle_ui.has_method("hide_target_selection"):
		battle_ui.hide_target_selection()


func handle_skill_command():
	# 这里简化处理，实际应该显示技能选择界面
	print("技能按钮被点击")
	if current_mode == BattleMode.COMMAND_PHASE:
		# 找到当前未分配指令的玩家角色
		var player = null
		for p in player_characters:
			if p.is_alive and p.name not in player_commands:
				player = p
				break

		if player:
			store_player_command(player, "skill", null)

	else:
		process_player_action("skill", null)


func handle_defend_command():
	# 在指令安排阶段，我们只是存储指令
	if current_mode == BattleMode.COMMAND_PHASE:
		# 找到当前未分配指令的玩家角色
		var player = null
		for p in player_characters:
			if p.is_alive and p.name not in player_commands:
				player = p
				break

		if player:
			store_player_command(player, "defend", null)

	else:
		# 在行动执行阶段，直接处理
		process_player_action("defend")


func handle_item_command():
	# 这里简化处理，实际应该显示物品选择界面
	print("物品按钮被点击")
	if current_mode == BattleMode.COMMAND_PHASE:
		# 找到当前未分配指令的玩家角色
		var player = null
		for p in player_characters:
			if p.is_alive and p.name not in player_commands:
				player = p
				break

		if player:
			store_player_command(player, "item", null)

	else:
		process_player_action("item", null)


# 处理敌人回合
func _process_enemy_turn(enemy: Enemy):
	# 获取敌人AI决策
	var battle_state = {
		"player_characters": player_characters,
		"enemy_characters": enemy_characters,
		"current_enemy": enemy
	}

	var action = enemy.get_ai_action(battle_state)
	current_state = BattleState.RESOLVING

	# 执行敌人行动
	match action["type"]:
		"attack":
			# 选择一个存活的玩家作为目标
			var target = _select_player_target()
			if target:
				var damage = enemy.attack
				var actual_damage = target.take_damage(damage)
				add_battle_log(
					"%s对%s造成了%d点伤害！" % [enemy.name, target.name, actual_damage],
					Color(1, 0.5, 0.5, 1)
				)
		"defend":
			add_battle_log("%s进入了防御状态！" % enemy.name, Color(0.8, 0.8, 0.8, 1))

	# # 行动完成，等待一段时间后进入下一回合
	# await battle_scene.get_tree().create_timer(1.0).timeout
	# proceed_to_next_turn()


# 选择玩家目标
func _select_player_target():
	var alive_players = []
	for player in player_characters:
		if player.is_alive:
			alive_players.append(player)

	if alive_players.size() > 0:
		return alive_players[randi() % alive_players.size()]
	return null


# 检查战斗是否结束
func _check_battle_end():
	# 检查所有敌人是否都已死亡
	var all_enemies_dead = true
	for enemy in enemy_characters:
		if enemy.is_alive:
			all_enemies_dead = false
			break

	if all_enemies_dead:
		current_state = BattleState.VICTORY
		add_battle_log("战斗胜利！", Color(1, 1, 0, 1))
		_end_battle(true)
		return true

	# 检查所有玩家是否都已死亡
	var all_players_dead = true
	for player in player_characters:
		if player.is_alive:
			all_players_dead = false
			break

	if all_players_dead:
		current_state = BattleState.DEFEAT
		add_battle_log("战斗失败！", Color(1, 0.2, 0.2, 1))
		_end_battle(false)
		return true

	return false


# 结束战斗
func _end_battle(_is_victory: bool):
	_enable_command_ui(false)
	# 这里可以添加战斗结束后的处理逻辑


# 启用/禁用命令UI
func _enable_command_ui(enable: bool):
	if battle_ui:
		if enable and battle_ui.has_method("enable_command_ui"):
			battle_ui.enable_command_ui()
		elif battle_ui.has_method("disable_command_ui"):
			battle_ui.disable_command_ui()


# 禁用命令UI（公共API）
func disable_command_ui():
	_enable_command_ui(false)


# 启用命令UI（公共API）
func enable_command_ui():
	_enable_command_ui(true)


# 添加战斗日志
func add_battle_log(message: String, color: Color = Color(1, 1, 1, 1)):
	battle_log.append(message)

	# 使用战斗UI组件显示日志
	if battle_ui and battle_ui.has_method("add_battle_log"):
		battle_ui.add_battle_log(message, color)
	# 所有行动日志直接输出到控制台
	print("【战斗日志】" + message)


# 开始战斗执行阶段
func start_battle_execution():
	"""当玩家安排完所有指令后调用，开始战斗执行阶段"""
	print("开始战斗执行阶段", current_mode == BattleMode.COMMAND_PHASE)
	if current_mode == BattleMode.COMMAND_PHASE:
		print("进入回合执行阶段")
		# 进入回合执行阶段
		determine_turn_order()  # 这会开始战斗执行过程


# 存储玩家命令
func store_player_command(player: Character, action_type: String, target: Character = null):
	if player.is_alive and player.name not in player_commands:
		player_commands[player.name] = {"action_type": action_type, "target": target}

		# 通知战斗场景该玩家已分配指令
		if battle_scene and battle_scene.has_method("assign_command_to_player"):
			battle_scene.assign_command_to_player(player.name, action_type, target)

		# 提供视觉反馈
		add_battle_log("%s的指令已安排！" % player.name, Color(0.5, 1, 0.5, 1))
